package com.crm.util;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.crm.pojo.common.UserContext;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        // 使用严格的填充策略
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());

        //填充创建人
        Object createBy = getCurrentUser();
        if (createBy != null){
            this.strictInsertFill(metaObject, "createBy", String.class, createBy.toString());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 只更新 updateTime 和 updateBy
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
         Object updateBy = getCurrentUser();
         if (updateBy != null) {
             this.strictUpdateFill(metaObject, "updateBy", String.class, updateBy.toString());
         }
    }

    /**
     * 获取当前用户信息（示例方法，需要根据实际项目调整）
     */
    private Object getCurrentUser() {
        // 这里可以根据实际项目情况获取当前用户
        // 例如从 SecurityContext、ThreadLocal 或其他上下文获取
        return UserContext.getCurrentUser().getUserName(); // 默认值
    }
}
